package cn.ichiva.mq;

import cn.ichiva.annotation.MQ;
import cn.ichiva.annotation.MQListener;
import org.springframework.aop.framework.AdvisedSupport;
import org.springframework.aop.framework.AopProxy;
import org.springframework.aop.support.AopUtils;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

/**
 * MQ服务实现
 * 1.实现ApplicationContextAware接口,获取监听类
 * 2.映射主题和处理方法
 * 3.对外提供生产接口
 */
@Component
public class MQService implements ApplicationContextAware {
    Map<String,Node> map = new HashMap<>();
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        Map<String, Object> rocketListeners = applicationContext.getBeansWithAnnotation(MQ.class);
        Collection<Object> beans = rocketListeners.values();
        for (Object bean : beans) {
            try {
                bean = getTarget(bean);
            } catch (Exception e) {}

            Method[] methods = bean.getClass().getMethods();
            for (Method method : methods) {
                MQListener annotation = method.getAnnotation(MQListener.class);
                if(null != annotation){
                    String tag = annotation.tag();
                    Node node = new Node();
                    node.setTag(tag);
                    node.setMethod(method);
                    node.setObj(bean);
                    map.put(tag,node);
                }
            }
        }
    }

    public void production(String tag, Object object) throws InvocationTargetException, IllegalAccessException {
        Node node = map.get(tag);
        node.getMethod().invoke(node.getObj(),object);
    }

    private static class Node{

        private String tag;
        private Object obj;
        private Method method;
        private Class<?> clazz;

        public String getTag() {
            return tag;
        }

        public void setTag(String tag) {
            this.tag = tag;
        }

        public Object getObj() {
            return obj;
        }

        public void setObj(Object obj) {
            this.obj = obj;
        }

        public Method getMethod() {
            return method;
        }

        public void setMethod(Method method) {
            this.method = method;
        }

        public Class<?> getClazz() {
            return clazz;
        }

        public void setClazz(Class<?> clazz) {
            this.clazz = clazz;
        }
    }



    /**
     * 获取 目标对象
     * @param proxy 代理对象
     * @return
     * @throws Exception
     */
    public static Object getTarget(Object proxy) throws Exception {

        if(!AopUtils.isAopProxy(proxy)) {
            return proxy;//不是代理对象
        }

        if(AopUtils.isJdkDynamicProxy(proxy)) {
            return getJdkDynamicProxyTargetObject(proxy);
        } else { //cglib
            return getCglibProxyTargetObject(proxy);
        }



    }


    private static Object getCglibProxyTargetObject(Object proxy) throws Exception {
        Field h = proxy.getClass().getDeclaredField("CGLIB$CALLBACK_0");
        h.setAccessible(true);
        Object dynamicAdvisedInterceptor = h.get(proxy);

        Field advised = dynamicAdvisedInterceptor.getClass().getDeclaredField("advised");
        advised.setAccessible(true);

        Object target = ((AdvisedSupport)advised.get(dynamicAdvisedInterceptor)).getTargetSource().getTarget();

        return target;
    }


    private static Object getJdkDynamicProxyTargetObject(Object proxy) throws Exception {
        Field h = proxy.getClass().getSuperclass().getDeclaredField("h");
        h.setAccessible(true);
        AopProxy aopProxy = (AopProxy) h.get(proxy);

        Field advised = aopProxy.getClass().getDeclaredField("advised");
        advised.setAccessible(true);

        Object target = ((AdvisedSupport)advised.get(aopProxy)).getTargetSource().getTarget();

        return target;
    }
}
